var _rolecontroller = CTX + '/sys/role';
var _authcontroller = CTX + '/sys/auth';
var Req = {
    rolePage: {method: 'GET', url: _rolecontroller},
    aclTree: {method: 'GET', url: _authcontroller + '/aclTree'},
    userList: {method: 'GET', url: _authcontroller + '/userList'},
    saveUsers: {method: 'POST', url: _authcontroller + '/saveUsers'},
    saveAcls: {method: 'POST', url: _authcontroller + '/saveAcls'}
};


var $roleGrid = null;
var userRelationInited = false;
var aclRelationInited = false;

$(function () {
    $.app.controlPermission();
    $roleGrid = $('#roleGrid');

    initRoleGrid();

    $('#searchBtn').click(function () {
        var params = getQueryParams();
        $roleGrid.datagrid('load', params);
    });

    $('#resetBtn').click(function () {
        $('#searchForm').form('reset');
        $('#searchBtn').trigger('click');
    });


});

function getQueryParams() {
    var params = $('#searchForm').serializeForm();
    return params;
}

function searchRole() {
    var params = getQueryParams();
    $roleGrid.datagrid('load', params);
}

function resetSearchRole() {
    $('#searchForm').form('reset');
    searchRole();
}

function initRoleGrid() {
    $roleGrid.datagrid({
        fit: true,
        fitColumns: true,
        pagination: false,
        method: Req.rolePage.method,
        url: Req.rolePage.url,
        queryParams: getQueryParams(),
        sortName: 'id',
        sortOrder: 'asc',
        columns: [[{
            field: 'name',
            title: '角色名称',
            width: 100,
            sortable: true
        }, {
            field: 'enname',
            title: '角色英文名',
            width: 100
        }]],
        onClickRow: function (index, row) {
            initAclAndUserRelation(row.id);
        },
        onLoadSuccess: function (data) {
            if (data && data.rows && data.rows.length > 0) {
                $roleGrid.datagrid('selectRow', 0);
                var role = data.rows[0];
                initAclAndUserRelation(role.id);
            }
        }
    });
}

function initAclAndUserRelation(roleId) {
    if (!aclRelationInited) {
        $('#roleAclTree').tree({
            method: Req.aclTree.method,
            url: Req.aclTree.url + '?roleId=' + roleId,
            checkbox: true,
            cascadeCheck: false,
            onBeforeCheck: function (node, checked) {
                if (typeof node.attributes.hasAcl === 'undefined') {
                    return false;
                } else if (!node.attributes.hasAcl) {
                    $.showMsg('没有权限的操作权限');
                    return false;
                }
            },
            onCheck: function (node, checked) {
                if (checked) { // 级联选中父节点
                    checkParent(this, node, true);
                } else {
                    checkChildren(this, node, true, false);
                }
            },
            loadFilter: function (data, parent) {
                var ret = [];
                if (data.data) {
                    ret = getTreeDataFromPageData_(data.data, 'id', 'name', 'children');
                }
                return ret;
            }
        });
    } else {
        $('#roleAclTree').tree({
            method: Req.aclTree.method,
            url: Req.aclTree.url + '?roleId=' + roleId
        });
    }


    $.ajax({
        method: Req.userList.method,
        url: Req.userList.url,
        data: {
            roleId: roleId
        },
        dataType: 'json',
        success: function (result) {
            if (result && result.status) {
                if (result.status == '200') {
                    var data = result.data;
                    var selectedHtml = '', unSelectedHtml = '';
                    if (data.select) {
                        for (var i = 0, len = data.select.length; i < len; i++) {
                            var s = data.select[i];
                            selectedHtml += $.app.formatString('<option value="{0}" selected="selected">{1}</option>', s.id, s.username);
                        }
                    }
                    if (data.unselect) {
                        for (var j = 0, l = data.unselect.length; j < l; j++) {
                            var us = data.unselect[j];
                            unSelectedHtml += $.app.formatString('<option value="{0}">{1}</option>', us.id, us.username);
                        }
                    }
                    $("#roleUserList").html(selectedHtml + unSelectedHtml);
                    if (!userRelationInited) {
                        $('select[name="roleUserList"]').bootstrapDualListbox({
                            nonSelectedListLabel: '待选用户列表',
                            selectedListLabel: '已选用户列表',
                            showFilterInputs: true,
                            moveOnSelect: false
                        });
                        userRelationInited = true;
                    } else {
                        $('select[name="roleUserList"]').bootstrapDualListbox('refresh', true);
                    }

                } else {
                    $.errorMsg(result.msg);
                }
            }
        }
    });
}

/**
 * 级联操作父节点
 * @param target
 * @param node
 * @param checked
 */
function checkParent(target, node, checked) {
    var parent = $(target).tree('getParent', node.target);
    if (parent) {
        if (checked) {
            $(target).tree('check', parent.target);
        } else {
            $(target).tree('uncheck', parent.target);
        }
        checkParent(target, parent, checked);
    }
}

/**
 * 级联操作子节点
 * @param target
 * @param node
 * @param deepCascade
 * @param checked
 */
function checkChildren(target, node, deepCascade, checked) {
    // 深度级联时先展开节点
    if (deepCascade) {
        $(target).tree('expand', node.target);
    }
    // 根据ID获取下层子节点
    var children = $(target).tree('getChildren', node.target);
    for (var i = 0; i < children.length; i++) {
        var child = children[i];
        if (checked) {
            $(target).tree('check', child.target);
        } else {
            $(target).tree('uncheck', child.target);
        }
        checkChildren(target, child, deepCascade, checked);// 递归选择子节点
    }
}

function saveRoleAcl() {
    var rows = $roleGrid.datagrid('getSelections');
    if (rows.length !== 1) {
        $.showMsg('请先在左侧选择要操作的角色');
    }

    var role = rows[0];
    var aclIds = getTreeSelectedAclId();
    $.ajax({
        type: Req.saveAcls.method,
        url: Req.saveAcls.url,
        data: {
            roleId: role.id,
            aclIds: aclIds.join(',')
        },
        dataType: 'json',
        success: function (result) {
            $.dealResultData(result);
        }
    });
}

function saveRoleUser() {
    var rows = $roleGrid.datagrid('getSelections');
    if (rows.length !== 1) {
        $.showMsg('请先在左侧选择要操作的角色');
    }

    var role = rows[0];
    var userIds = $("#roleUserList").val() ? $("#roleUserList").val().join(",") : '';
    $.ajax({
        type: Req.saveUsers.method,
        url: Req.saveUsers.url,
        data: {
            roleId: role.id,
            userIds: userIds
        },
        dataType: 'json',
        success: function (result) {
            $.dealResultData(result);
        }
    });
}

function getTreeSelectedAclId() {
    var ids = [];
    var nodes = $('#roleAclTree').tree('getChecked');
    if (nodes && nodes.length > 0) {
        $.each(nodes, function (i, node) {
            if (node.attributes.type || node.attributes.type === 0) {
                ids.push(node.id);
            }
        });
    }
    return ids;
}

function fmtTreeName(d) {
    if (!d['hasAcl']) {
        return '<span style="color:grey;">' + d['name'] + '</span>';
    }
    return d['name'];
}

/**
 * 把后台返回的tree结构处理成easyui-tree可用的结构
 * @param dataList
 * @param idProp
 * @param nameProp
 * @param childrenProp
 * @returns {Array}
 */
function getTreeDataFromPageData_(dataList, idProp, nameProp, childrenProp) {
    var treeData = [];
    $.each(dataList, function (i, d) {
        var node = {
            'id': d[idProp],
            'text': fmtTreeName(d),
            'checked': d.checked,
            'attributes': {}
        };
        for (var prop in d) {
            if (prop !== childrenProp) {
                node.attributes[prop] = d[prop];
            }
        }

        var children = d[childrenProp];
        if (children && children.length > 0) {
            node.state = 'open';
            node.children = getTreeDataFromPageData_(children, idProp, nameProp, childrenProp);
        }
        treeData.push(node);
    });
    return treeData;
}